package pers.kw.utils;

import cn.hutool.core.lang.Assert;
import com.github.pagehelper.Page;
import pers.kw.entity.BaseEntity;
import pers.kw.entity.PageDto;
import pers.kw.entity.TokenDto;
import pers.kw.enums.YesOrNoEnum;
import pers.kw.protocol.TokenContext;

import java.util.Date;

/**
 * DO基础字段设置工具方法、分页结果封装工具方法
 */
public class DoWrapUtil {

    public static <T extends BaseEntity> T insert(T t, boolean ignoreBizCode, boolean loginFlag) {
        Assert.notNull(t, "t is can not null");
        t.setCreatedTime(new Date());
        t.setYn(YesOrNoEnum.YES.getCode());
        t.setVersion(1L);
        if (loginFlag) {
            TokenDto tokenDto = TokenContext.current();
            Assert.notNull(tokenDto, "token is can not null");
            t.setCreatedMobile(tokenDto.getMobile());
            t.setCreatedCode(tokenDto.getUserNo());
            t.setCreatedName(tokenDto.getUserName());
        } else {
            t.setCreatedMobile(null);
            t.setCreatedCode(null);
            t.setCreatedName("系统");
            t.setCreatedCode("0");
            t.setCreatedMobile("");
        }
        if (!ignoreBizCode) {
            t.setBizCode(String.valueOf(SnowFlake.nextId()));
        }
        return t;
    }

    /**
     * 功能描述: 设置更新人基本字段（）
     */
    public static <T extends BaseEntity> T update(T t, boolean loginFlag) {
        Assert.notNull(t, "t is can not null");
        if (loginFlag) {
            TokenDto tokenDto = TokenContext.current();
            Assert.notNull(tokenDto, "token is can not null");
            t.setModifiedCode(tokenDto.getUserNo());
            t.setModifiedName(tokenDto.getUserName());
            t.setModifiedMobile(tokenDto.getMobile());
        } else {
            t.setModifiedCode(null);
            t.setModifiedName("系统");
            t.setModifiedMobile(null);
        }
        t.setModifiedTime(new Date());
        return t;
    }

    /**
     * 封装分页数据
     */
    public static <T> PageDto<T> page(Page<T> selectResult) {
        if (selectResult.getResult().isEmpty()) {
            selectResult.setPageNum(1);
        }
        PageDto<T> result = new PageDto<>();
        result.setTotal(selectResult.getTotal());
        result.setPageNum(selectResult.getPageNum());
        result.setPageSize(selectResult.getPageSize());
        result.setPages((long) selectResult.getPages());
        result.setList(selectResult.getResult());
        return result;
    }

}
